package com.kaguya.vams.controller;

import com.google.code.kaptcha.Producer;
import com.kaguya.vams.common.constant.Constants;
import com.kaguya.vams.domain.Result;
import com.kaguya.vams.utils.IdUtils;
import com.kaguya.vams.utils.MapUtils;
import com.kaguya.vams.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * 验证码 controller
 *
 * @author : kaguya
 * @date : 18:22 2021/7/29
 */
@Slf4j
@RestController
public class CaptchaController extends BaseController {
    // HttpServletRequest 位于BaseController中

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private RedisUtils redisUtils;

    @GetMapping("/captcha")
    public Result getCaptcha() {

        //如果redis中有验证码，将其清空
        String getImgKey = req.getParameter("imgKey");
        log.info("获取验证码 - ");
        if(getImgKey != null && !StringUtils.isBlank(redisUtils.getCacheObject(getImgKey)) ) {
            //System.out.println("有旧验证码");
            redisUtils.deleteObject(getImgKey);
        }

        //保存验证码信息 key/verifyKey - v/code
        String uuid = IdUtils.simpleUUID();
        //key
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;



        //设置验证码文字以及图片
        String code = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(code);

        //测试 先写死
        //verifyKey = "11111";
        //code = "11111";

        //存入redis key v 有效时间(2） 单位（分钟）
        redisUtils.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return Result.fail(e.getMessage());
        }

        //转换为base64格式
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(os.toByteArray());

        //HashMap<String, Object> map = new HashMap<>();
        //
        //map.put("token", verifyKey);
        //map.put("captchaImg", base64Img);

        HashMap<String, Object> map = MapUtils
                .build()
                .put("imgKey", verifyKey)
                .put("captchaImg", base64Img);
        //System.out.println(map.get("token"));
        return Result.ok(map);
    }
}
